package com.taiji.dianthus.controller;


import com.taiji.dianthus.common.BasicController;
import com.taiji.dianthus.domain.sys.DSysUser;
import com.taiji.dianthus.security.DianthusAuthenticationProvider;
import com.taiji.dianthus.security.DianthusSecurityMetadataSource;
import com.taiji.dianthus.security.DianthusUserDetailServiceImpl;
import com.taiji.dianthus.service.http.HttpAPIService;
import com.taiji.dianthus.service.sys.MenuService;
import com.taiji.dianthus.service.sys.SysLogService;
import com.taiji.dianthus.service.sys.UserService;
import com.taiji.dianthus.util.IPUtil;
import com.taiji.dianthus.util.RestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

import static com.taiji.dianthus.common.Constant.LOG_OPERATION_LOGIN;

/**
 * @ClassName LoginViewController
 * @Description 登录页面
 * @Author H.M
 * @Date 2019/10/22
 */
@Controller
@RequestMapping
public class LoginViewController extends BasicController {

    @Autowired
    private SysLogService sysLogService;
    @Autowired
    private RestUtil restUtil;
    @Autowired
    private DianthusSecurityMetadataSource dianthusSecurityMetadataSource;
    @Autowired
    private DianthusUserDetailServiceImpl userDetailsService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserService userService;
    @Autowired
    private HttpAPIService httpAPIService;

    private DianthusAuthenticationProvider dianthusAuthenticationProvider = new DianthusAuthenticationProvider();
    @Autowired
    private DianthusUserDetailServiceImpl dianthusUserDetailService;

    @Value("${zhicheng.url}")
    private String zhichengUrl;
    @Value("${app.field.name}")
    private String appFieldName;


    /**
     * 页面拦截
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/")
    public String showMain(HttpServletRequest request, Model model, RedirectAttributes attr) {
        DSysUser user = currentUser();
        attr.addFlashAttribute("loginPage", "loginPage");//跳转地址不带上u2参数
        sysLogService.save(user, LOG_OPERATION_LOGIN,
                IPUtil.getIpAddr(request), "登录系统", 1, "登录成功");
        return "redirect:/home/index";
    }


    /**
     * 门户跳转
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/ssoLogin")
    public String ssoLogin(HttpServletRequest request, Model model, String userId) {
        Map<String, Object> params = new HashMap<>();
        try {
           /* params.put("appFieldName", URLEncoder.encode(EncryptUtil.AESEncrypt(appFieldName)));
            params.put("userId", URLEncoder.encode(EncryptUtil.AESEncrypt(userId)));
            BusinessMessage oo = httpAPIService.doPost(zhichengUrl, params);
            //  JSONObject oo = restUtil.postForm(zhichengUrl, params);
            if (oo != null && oo.getSuccess()) {
                JSONObject ooo = (JSONObject) oo.getData();*/
            DSysUser user = userService.getByPushId(userId);
                /*if (user == null) {
                    return "/pages/common/syn_login_error";
                }
                sysLogService.save(user, LOG_OPERATION_LOGIN,
                        IPUtil.getIpAddr(request), "登录系统", 1, "登录成功");
                request.getSession().setAttribute(StaticKeys.LOGIN_KEY, user);*/
            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(user.getUserLoginName(), user.getUserPassword());
            authentication.setDetails(new WebAuthenticationDetails((HttpServletRequest) request));
            //  UserDetails userDetails = userDetailsService.loadUserByUsername(user.getUserLoginName());
            this.dianthusSecurityMetadataSource.setMenuService(menuService);
            this.dianthusSecurityMetadataSource.setUserService(userService);
            this.dianthusAuthenticationProvider.setPmUserDetailService(dianthusUserDetailService);
            Authentication result = dianthusAuthenticationProvider.authenticate(authentication);
            SecurityContextHolder.getContext().setAuthentication(result);
            model.addAttribute("userName", user.getName());
            System.out.println("认证：" + SecurityContextHolder.getContext().getAuthentication());
            return "redirect:/";
            /*}*/
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "/pages/common/syn_login_error";
    }
}



